<template>
  <div class="article">
    <a-skeleton :loading="loading">
      <div v-if="!is404error" class="cl-artical-content">
        <h2 class="cl-artical-title">{{blogdetail.Title}}</h2>
        <div class="cl-card-tag">
            <div class="f-fl fs-14">
              <span>作者：{{blogdetail.Publisher}}</span>
              <span class="ml10">围观群众：<i class="readcount">{{getVisitCount(blogdetail.Id)}}</i></span>
              <span class="ml10">更新于 <label>{{blogdetail.UpdatedOnTime | formatDate('yyyy-MM-dd hh:mm')}}</label></span>
            </div>
            <div class="f-fr fs-14 likeit">
              <a-avatar class="article-icon-like" :style="{ verticalAlign: 'middle' }" @click.once="likeit(blogdetail.Id)">
                <a-icon slot="icon" type="like" />
              </a-avatar>
              <span class="like-count">{{bloglikecount}}</span>
              <span class="animateaddone" :class="{ 'animated slideOutRight': ilikeit}" ref="animateadd">+1</span>
            </div>
        </div>
        <div class="cl-artical" v-if="showimglist">
          <viewer :images="blogdetail.ImageUrls" class="images clearfix">
            <template slot-scope="scope">
              <img v-for="src in scope.images" v-lazy="'/images' + src" :key="src" class="image" />
            </template>
          </viewer>
        </div> 
        <div class="cl-artical" v-html="blogdetail.Contents" v-hljs></div> 
        <div class="cl-card-tag" style="margin-top: 20px">
            <div class="fs-18 tags" v-if="tags.length > 0">
              <a-icon type="tags" class="f-fl"/>
              <ul class="label f-fl">
                <li v-for="(tag, index) in tags" :key="index">
                  <a href="#">{{tag}}</a>
                </li>
              </ul>
            </div>
        </div>
      </div>
      <div v-else class="error404">
        <h3>对不起！发生了一些意想不到的错误。</h3>
		    <h4>请求的资源或已删除或不存在，看看其他的吧...</h4>
		    <p>你很优秀你造吗？居然能找到这里来，想要骗取我的公交卡密码吗...</p>
      </div>
    </a-skeleton>
    <div class="recommend-panel">
      <div class="copyright mt20">
        <p class="f-toe fc-black">
          非特殊说明，本文版权归 博主 所有，转载请注明出处.
        </p>
        <p class="f-toe">
          本文网址：
          <a :href="blogurl">{{blogurl}}</a>
        </p>
      </div>            
    </div>
  </div>
</template>

<script>
import animate from 'animate.css'
import '@/assets/css/tinymcecontent.min.css'
import 'viewerjs/dist/viewer.css'
import Viewer from "v-viewer/src/component.vue"
import 'highlight.js/styles/railscasts.css';
import lodash from 'lodash'
import { mapState } from 'vuex'
import { getBlogDetail, logLikeBlog } from '@/api'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
export default {
  name: 'BlogDetail',
  components: {
    Viewer
  },
  data() {
    return {
      columnid: 0,
      blogid: 0,
      loading: true,
      is404error: false,
      showimglist: false,
      pagelayout: 'DefaultSinglePage',
      blogdetail: {},
      tags: [],
      blogStatistics: [],
      ilikeit: false,
      bloglikecount: 0,
      blogurl: ''
    };
  },
  computed: {
    ...mapState({
      mainmenu: state => state.navmenus
    })
  },
  mounted () {
    this.onLoadDetail()
  },
  watch: {      
    $route: function () {
      this.blogid = this.columnid = 0;
      this.onLoadDetail()
    }
  },
  methods: {
    onLoadDetail() {
      this.blogurl = window.location.href;
      const navimenus = this.mainmenu;
      let activeMenuItem = null;
      if(!lodash.isNil(this.$route.params.columnid)) { //Detail
          this.columnid = this.$route.params.columnid;
          if(typeof this.columnid === 'string') this.columnid = parseInt(this.$route.params.columnid);
          activeMenuItem = lodash.find(navimenus, ['Id', this.columnid])
          if(!lodash.isNil(activeMenuItem)) {
              this.pagelayout = activeMenuItem.LayoutDetailTemplate
              this.remoteLoadData();
          }
          else this.$route.push("bloghome")
      }
      else this.$route.push("bloghome")
    },
    remoteLoadData() {
      this.loading = this.is404error = true;
      if(this.blogid <= 0) //Get cache first if initialized
        this.blogid = (!lodash.isNil(this.$route.params.blogid)) 
                    ? this.$route.params.blogid
                    : 0; 
      let me = this;
      getBlogDetail(this.blogid, this.columnid,
          function(res) { //Success
            me.loading = me.is404error = false;
            me.blogdetail = res.data
            setDocumentTitle(`${me.blogdetail.Title} - ${domTitle}`)
            if(!lodash.isNil(me.blogdetail.ImageUrls)) 
              me.showimglist = me.blogdetail.ImageUrls.length > 0; 
            if(!lodash.isEmpty(res.data.CustomProperties)) {
              const blogcount = res.data.CustomProperties.BlogStatistics                
              if(blogcount !== null) {
                me.blogStatistics = blogcount
                me.bloglikecount = me.getLikeCount(me.blogid);
              }
            }     
            if(!lodash.isNil(me.blogdetail.Tags))
              me.tags = me.blogdetail.Tags.trim() === "" ? [] : lodash.split(me.blogdetail.Tags, ',');

            //将文章内容(Contents)中有本地上传的图片通过绑定代理替换后显示
            if(!lodash.isNil(me.blogdetail.Contents)){
              let textareaHtml = me.blogdetail.Contents;  //从response获取HTML的数据
              const srcReg = /(..\/){2}(uploaded)/igm;
              if(textareaHtml) {
                me.blogdetail.Contents = textareaHtml.replace(srcReg,"/images/uploaded");
                //hljs.initHighlightingOnLoad()
              }                
            }
          }, function(res) { //Failure
            me.loading = false;
            me.is404error = true;
            if(typeof res === 'string') { //res as message
              me.$notification['error']({
                  message: '通知消息',
                  description: res,
              });
            } else {
              if(res.state === 308) {
                this.$route.push({ path: res.data })
                return false;
              }             
              me.is404error = (res.state === 404) ? true : false;
            }
          }
      );
    },
    /**
     * 后台返回以博客Id，访问数量的统计数据形如：
     * "BlogStatistics": [
     *  {
     *    "Id": 10,
     *    "VisitCount": 0,
     *    "LikeCount": 4
     *  }
     * ]
     * 遍历分页列表Id获取对应Id的统计信息
     */
    filterBlogInfo(blogid) {
      if (typeof blogid === 'string') blogid = parseInt(blogid)
      if (blogid <= 0) return null
      const bloginfo = lodash.find(this.blogStatistics, ['Id', blogid]);
      return (typeof bloginfo === "undefined") ? null : bloginfo;
    },
    /**
     * 数据说明同filterBlogInfo
     * 遍历分页列表Id获取对应Id的浏览量
     */
    getVisitCount(blogid) {
      if (!blogid) return 0
      const bloginfo = this.filterBlogInfo(blogid)
      return (bloginfo === null) ? 0 : bloginfo.VisitCount;
    },
    /**
     * 数据说明同filterBlogInfo
     * 遍历分页列表Id获取对应Id的点赞量
     */
    getLikeCount(blogid) {
      if (!blogid) return 0
      const bloginfo = this.filterBlogInfo(blogid)
      return (bloginfo === null) ? 0 : bloginfo.LikeCount;
    },
    /**
     * 通过事件修饰符 click.once 确保点赞每个页面渲染后只触发一次
     */
    likeit(blogid) {
      let me = this;
      me.$refs.animateadd.style.display="block";
      logLikeBlog(me.blogid); //不需要回调，无论api成功失败都显示动画效果
      me.ilikeit = true;
      setTimeout(function(){
        me.bloglikecount += 1;      
  		},800)
    }
  }
}
</script>

<style lang="less">
  .article {
    text-align: left;
    .cl-artical-content,
    .error404 {
      min-height: 450px;
      background-color: #fff;
      padding: 25px;
    }
    .copyright {
      clear: both;
      line-height: 22px;
      text-shadow: 0 1px 0 rgba(255,255,255,.8);
      font-size: 12px;
      color: #787977;

      .f-toe {
        overflow: hidden;
        word-wrap: normal!important;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
  i.readcount {
    font-style: italic;
  }
  .image {
    height: 200px;
    cursor: pointer;
    margin: 5px;
    display: inline-block;
  }
  .likeit { 
    position: relative; 
    .animateaddone {
      position: absolute;
      top: 5px;
      left: 12px;
      font-size: 16px;
      color: red;
      animation-duration: 1s;
      display: none;
    }

  }
  .article-icon-like {
    background-color:rgba(126,107,1,.08);
    &:hover {
      cursor: pointer;
      background-color: #e7672e;
    }
    .anticon-like{
      color: #eb2f96;
      top: -5px;
      position: relative;
    }
  }
  .article-icon-like:hover .anticon-like{
    color: white;
    transform:scale(1.4)
  }
  span.like-count {
    font-weight: 700;
    color: #e7672e;
    &:before {
      content: " x ";
    }
  }
  .cl-card-tag .tags {
    background-color: #F8F8F8;
    line-height: 44px;
    height: 44px;
    padding: 5px 0 5px 10px;
    border: 1px solid #F0F0F0;

    .anticon-tags {
      position: relative;
      top: 8px;
    }
    .label {
      position: relative;
      margin: 0 0 0 15px;
      padding: 0;

      a {
        height: 30px;
        line-height: 30px;
        margin: 0 5px;
      }
    }
  }
</style>